﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TTQT;
using TTQT.TTQT_Code;

public partial class XuatBanHang : MasterControl// System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            txtCK.Attributes.Add("onkeyup", "ckLostFocus();");
            txtCK.Attributes.Add("ondblclick", "selectText(this)");

            txtGiaBan.Attributes.Add("onkeyup", "gbLostFocus();");
            txtGiaBan.Attributes.Add("ondblclick", "selectText(this)");

            bindKhachHang();
            bindDetailGrid();
            //cmdView.Attributes.Add("onclick", "openPageXemGiaoDich('GiaoDich/InPhieuXuatKho.aspx?MaHoaDon=" + lblMaHoaDon.Text + "'); return false;");
            cmdView.Attributes.Add("onclick", "xemHoaDon();");
            visiPane(true, false);
        }
        if (lblMaHoaDon.Text.Length > 1)
        {
            cmdView.Enabled = true;
        }
    }
    private void bindDetailGrid()
    {
        if (lblMaHoaDon.Text.Length < 1)
        {
            dsDetail.SelectCommandType = SqlDataSourceCommandType.Text;
            dsDetail.SelectCommand = "select Id,Seri,TenHang,SoLuong,GiaBanThamkhao,ChietKhau,GiaBanThucTe from Hoadon_detail_temp where maHoaDon='" + UserInfo.userName + "'";
            try
            {
                ds.SelectCommand = "select sum(giaBanThucTe) from Hoadon_detail_temp where MaHoaDon='" + UserInfo.userName + "'";
                DataView dv = (DataView)ds.Select(new DataSourceSelectArguments());
                txtCongTien.Text = TTQTCommon.ToNumberFormat(dv.Table.Rows[0][0].ToString());
            }
            catch (Exception tong) {}
        }
        else
        {
            dsDetail.SelectCommandType = SqlDataSourceCommandType.Text;
            dsDetail.SelectCommand = "select Id,Seri,TenHang,SoLuong,GiaBanThamkhao,ChietKhau,GiaBanThucTe from Hoadon_detail where maHoaDon='" + lblMaHoaDon.Text + "'";
            try
            {
                ds.SelectCommand = "select sum(giaBanThucTe) from HoaDon_detail where MaHoaDon='" + lblMaHoaDon.Text + "'";
                DataView dv = (DataView)ds.Select(new DataSourceSelectArguments());
                txtCongTien.Text = TTQTCommon.ToNumberFormat(dv.Table.Rows[0][0].ToString());
            }
            catch (Exception tong) { }
        }
    }
    private void visiPane(bool pnBan, bool pnXem)
    {
        pnBanHang.Visible = pnBan;
        pnXemHoaDon.Visible = pnXem;
    }
    private void xemHoaDon()
    {
        lblDetailGrid.Text = "";
        double tongTien = 0;
        ds.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
        ds.SelectCommand = "HoaDon_Detail_getByMaHoaDon_print";
        ds.SelectParameters.Clear();
        ds.SelectParameters.Add(new Parameter("mahoadon"));
        ds.SelectParameters["mahoadon"].DefaultValue = lblMaHoaDon.Text;
        DataTable t = ((DataView)(ds.Select(new DataSourceSelectArguments()))).ToTable();
        int stt = 1;
        foreach (DataRow r in t.Rows)
        {
            lblDetailGrid.Text = lblDetailGrid.Text + @"<tr>
            <td class=tdDep>" + stt.ToString() + "</td>" +
                                 "<td class=tdDep>" + r["Seri"].ToString() + "</td>" +
                                 "<td class=tdDep>" + r["TenHang"].ToString() + "</td>" +
                                 "<td class=tdDep>" + TTQTCommon.ToNumberFormat(r["GiaBanThamKhao"].ToString()) + "</td>" +
                                 "<td class=tdDep>" + TTQTCommon.ToNumberFormat(r["ChietKhau"].ToString()) + "</td>" +
                                 "<td class=tdDep align=right>" + TTQTCommon.ToNumberFormat(r["GiaBanThucTe"].ToString()) + "</td></tr>";
            tongTien = tongTien + double.Parse(r["GiaBanThucTe"].ToString());
            stt++;
        }
        //Lấy thông tin hóa đơn
        ds.SelectCommand = "HoaDon_Master_getByMaHoaDon_print";
        ds.SelectParameters.Clear();
        ds.SelectParameters.Add(new Parameter("mahoadon"));
        ds.SelectParameters["mahoadon"].DefaultValue = lblMaHoaDon.Text;
        DataTable rs = ((DataView)ds.Select(System.Web.UI.DataSourceSelectArguments.Empty)).ToTable();
        if (rs != null)
        {
            try
            {
                lblChiNhanh.Text = UserInfo.TenChiNhanh;
                lblNgay.Text = rs.Rows[0]["NgayBan"].ToString();
                lblKhachHang.Text = rs.Rows[0]["Ten"].ToString();
                lblNoiDung.Text = rs.Rows[0]["NoiDung"].ToString();
            }
            catch { }
        }
    }
    private void bindKhachHang()
    {
        dsKhachHang.SelectCommandType = SqlDataSourceCommandType.Text;
        dsKhachHang.SelectCommand = "select id=0,ten='--------------' union select Id,Ten from KHNCC where MaCN='" + UserInfo.Brn_Code + "'";
        cboKhachHang.DataSourceID = "dsKhachHang";
        cboKhachHang.DataBind();
    }
    protected void cmdThem_Click(object sender, EventArgs e)
    {
        string sql = "";
        SqlConnection conn = new SqlConnection(TTQTCommon.DBConnectionString);
        SqlCommand comm = new SqlCommand();
        SqlTransaction tran = null;
        try
        {
            conn.Open();
            tran = conn.BeginTransaction();
            comm.Connection = conn;
            comm.Transaction = tran;
            string maHoaDon = lblMaHoaDon.Text.Length > 0 ? lblMaHoaDon.Text : UserInfo.userName;
            sql = "insert into HoaDon_detail_temp(seri,ngayBan,MaNhom,MaCN,Tenhang,picUrl,MaVach,GiaBanThamKhao,ChietKhau,GiaBanThucTe,SoLuong,UserName,MaHOaDon)" +
                        "select seri,NgayNhap,MaNhom,MaCN,TenHang,PicUrl,MaVach,GiaBanThamKhao,ChietKhau,GiaBanThamKhao-giaBanThamKhao*ChietKhau/100,1,'" + UserInfo.userName + "','" + maHoaDon + "'" +
                "from khohang where seri='" + txtMa.Text + "' and daban=0 and MaCN='" + UserInfo.Brn_Code + "'";
            comm.CommandText = sql;
            comm.CommandType = CommandType.Text;
            int maDetail = TTQTCommon.ToInt32(comm.ExecuteNonQuery(), 0);
            comm.Parameters.Clear();
            //Nếu insert Detail thành công thì update trạng thái DaBan trong bảng KhoHang
            if (maDetail > 0)
            {
                sql = "update KhoHang set daban=1 where seri='" + txtMa.Text + "' and MaCN='" + UserInfo.Brn_Code + "'";
                comm.Parameters.Clear();
                comm.CommandText = sql;
                maDetail = comm.ExecuteNonQuery();
            }
            if (maDetail > 0)
            {
                comm.Transaction.Commit();
            }
            else
            {
                comm.Transaction.Rollback();
            }
            bindDetailGrid();
            //detailGrid.DataBind();
            txtMa.Text = "";
            //try
            //{

            //    sql = "select sum(giaBanThucTe) from HoaDon_detail_temp where MaHoaDon='" + UserInfo.userName + "'";
            //    comm.CommandText = sql;
            //    txtCongTien.Text = comm.ExecuteScalar().ToString();
            //}
            //catch (Exception tong) { }
        }
        catch (Exception loi)
        {
            //Dong connection
            comm.Transaction.Rollback();
        }
        finally
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }

        }
    }
    protected void detailGrid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
    {

    }
    private void vsForm(bool detailG, bool pnck, bool cmdsave, bool cmdtimkiem)
    {
        detailGrid.Visible = detailG;
        pnCK.Visible = pnck;
        cmdSave.Visible = cmdsave;
        cmdTimKiem.Visible = cmdtimkiem;
    }
    protected void detailGrid_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        if (e.CommandName.Equals("cmdCK"))
        {
            this.lblSeri.Text = e.Item.Cells[1].Text;
            txtGiaGoc.Text = e.Item.Cells[4].Text;
            txtCK.Text = e.Item.Cells[5].Text;
            txtGiaBan.Text = e.Item.Cells[6].Text;
            //detailGrid.Visible = false;
            //pnCK.Visible = true;
            vsForm(false, true, false, false);
        }
        if (e.CommandName.Equals("cmdDelete"))
        {
            string sql = "";
            SqlConnection conn = new SqlConnection(TTQTCommon.DBConnectionString);
            SqlCommand comm = new SqlCommand();
            SqlTransaction tran = null;
            try
            {
                conn.Open();
                tran = conn.BeginTransaction();
                comm.Connection = conn;
                comm.Transaction = tran;
                sql = "Delete Hoadon_detail_temp where id=" + e.Item.Cells[0].Text;
                comm.CommandText = sql;
                comm.CommandType = CommandType.Text;
                int maDetail = TTQTCommon.ToInt32(comm.ExecuteNonQuery(), 0);
                comm.Parameters.Clear();
                //Nếu xoa Detail thành công thì update trạng thái DaBan trong bảng KhoHang
                if (maDetail > 0)
                {
                    sql = "update KhoHang set daban=0 where seri='" + e.Item.Cells[1].Text + "' and MaCN='" + UserInfo.Brn_Code + "'";
                    comm.Parameters.Clear();
                    comm.CommandText = sql;
                    maDetail = comm.ExecuteNonQuery();
                }
                if (maDetail > 0)
                {
                    comm.Transaction.Commit();
                }
                else
                {
                    comm.Transaction.Rollback();
                }
                bindDetailGrid();
                //detailGrid.DataBind();
                txtMa.Text = "";
                try
                {

                    sql = "select sum(giaBanThucTe) from HoaDon_detail_temp where MaHoaDon='" + UserInfo.userName + "'";
                    comm.CommandText = sql;
                    txtCongTien.Text = comm.ExecuteScalar().ToString();
                }
                catch (Exception tong) { }

            }
            catch (Exception loi)
            {
                //Dong connection
                comm.Transaction.Rollback();
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }
    }
    protected void detailGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        e.Item.Cells[4].Text = TTQTCommon.ToNumberFormat(e.Item.Cells[4].Text);
        e.Item.Cells[5].Text = TTQTCommon.ToNumberFormat(e.Item.Cells[5].Text);
        e.Item.Cells[6].Text = TTQTCommon.ToNumberFormat(e.Item.Cells[6].Text);
        try
        {
            Button del = (Button)e.Item.FindControl("cmdDelete");
            if (lblMaHoaDon.Text.Length > 0)
            {
                del.Visible = false;
            }
        }
        catch { }

    }
    protected void cmdSave_Click(object sender, EventArgs e)
    {
        if(cboKhachHang.SelectedValue.Equals("0"))
        {
            MyWebUtils.MyWebUtil.alert(this.Page,"Ban chua chon khach hang!");
            return;
        }
        SqlConnection conn = new SqlConnection(TTQTCommon.DBConnectionString);
        SqlCommand comm = new SqlCommand();
        SqlTransaction tran = null;
        try
        {
            conn.Open();
            tran = conn.BeginTransaction();
            comm.Connection = conn;
            comm.Transaction = tran;
            comm.CommandType = CommandType.StoredProcedure;
            comm.CommandText = "HoaDon_Master_Insert";
            comm.Parameters.Clear();
            //comm.Parameters.AddWithValue("@MaHoaDon", lblMaHoaDon.Text);
            comm.Parameters.AddWithValue("@UserName", UserInfo.userName);
            comm.Parameters.AddWithValue("@KHNCCID", cboKhachHang.SelectedValue);
            comm.Parameters.AddWithValue("@NoiDung", txtNoiDung.Text);
            comm.Parameters.AddWithValue("@LoaiGiaoDich", 0);
            comm.Parameters.AddWithValue("@TrangThai", 1);
            comm.Parameters.AddWithValue("@MaCN", UserInfo.Brn_Code);
            comm.Parameters.AddWithValue("@TongTien", txtCongTien.Text.Replace(",", ""));
            string maHoaDon = TTQTCommon.ToString(comm.ExecuteScalar());
            if (maHoaDon != null)
            {
                comm.Transaction.Commit();
                lblMaHoaDon.Text = maHoaDon;
                bindDetailGrid();
                visiPane(false, true);
                xemHoaDon();
                lblTongTienBangSo.Text = txtCongTien.Text;
            }
            else
            {
                comm.Transaction.Rollback();
            }
            //detailGrid.DataBind();
            txtMa.Text = "";
        }
        catch (Exception loi)
        {
            //Dong connection
            comm.Transaction.Rollback();
        }
        finally
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }
        }
    }
    protected void cmdCancel_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(TTQTCommon.DBConnectionString);
        SqlCommand comm = new SqlCommand();
        try
        {
            conn.Open();

            comm.Connection = conn;
            comm.CommandType = CommandType.StoredProcedure;
            comm.CommandText = "HoaDon_Master_Delete";
            comm.Parameters.Clear();
            comm.Parameters.AddWithValue("@MaHoaDon", lblMaHoaDon.Text);
            comm.Parameters.AddWithValue("@MaCN", UserInfo.Brn_Code);
            comm.Parameters.AddWithValue("@UserName", UserInfo.userName);
            if(comm.ExecuteNonQuery()>0)
            {
                Response.Redirect(Request.Url.ToString());
            }
            bindDetailGrid();
            visiPane(false, true);
            xemHoaDon();

            //detailGrid.DataBind();
            txtMa.Text = "";
        }
        catch (Exception loi)
        {

        }
        finally
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }
        }
    }
    protected void cmdTimKiem_Click(object sender, EventArgs e)
    {
        
    }
    protected void cmdAddNew_Click(object sender, EventArgs e)
    {
        Response.Redirect(Request.Url.ToString());
    }

    protected void cmdSaveCK_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(TTQTCommon.DBConnectionString);
        SqlCommand comm = new SqlCommand();
        try
        {
            conn.Open();

            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "Update Hoadon_detail_temp set chietKhau=" + txtCK.Text + ",GiaBanThucTe=" +
                               txtGiaBan.Text.Replace(",", "") + " where MaCN='" + UserInfo.Brn_Code + "' and UserName='"+UserInfo.userName+"' and seri='"+lblSeri.Text+"'";
            if (comm.ExecuteNonQuery() > 0)
            {
                bindDetailGrid();
                vsForm(true,false,true,true);
            }
            else
            {
                
            }
        }
        catch (Exception loi)
        {

        }
        finally
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }
        }
    }
    protected void cmdBoCK_Click(object sender, EventArgs e)
    {
        vsForm(true, false, true, true);
    }
}
